<template>
	<div class="editor-wrapper">
		<div :id="editorId"></div>
	</div>
</template>

<script>
import Editor from 'wangeditor';
import 'wangeditor/release/wangEditor.min.css';
import { oneOf } from '@/libs/tools';
import { getToken, getBaseUrl } from '@/libs/util.js';
export default {
	name: 'Editor',
	props: {
		value: {
			type: String,
			default: ''
		},
		/**
		 * 绑定的值的类型, enum: ['html', 'text']
		 */
		valueType: {
			type: String,
			default: 'html',
			validator: val => {
				return oneOf(val, ['html', 'text']);
			}
		},
		/**
		 * @description 设置change事件触发时间间隔
		 */
		changeInterval: {
			type: Number,
			default: 200
		},
		/**
		 * @description 是否开启本地存储
		 */
		cache: {
			type: Boolean,
			default: true
		}
	},
	computed: {
		editorId() {
			return `editor${this._uid}`;
		}
	},
	methods: {
		setHtml(val) {
			this.editor.txt.html(val);
		},
		getNotice(text) {
			this.$Notice.warning({
				title: '上传图片错误提示',
				desc: text
			});
		}
	},
	mounted() {
		this.editor = new Editor(`#${this.editorId}`);
		var _this = this;
		this.editor.customConfig.uploadImgHooks = {
			fail: function(xhr, editor, result) {
				_this.getNotice(result.message);
			},
			error: function(xhr, editor) {
				_this.getNotice('上传失败，请重新上传');
			}
		};
		this.editor.customConfig.customAlert = function(info) {};
		this.editor.customConfig.uploadImgMaxLength = 1;
		this.editor.customConfig.uploadFileName = 'file';
		this.editor.customConfig.uploadImgServer = getBaseUrl() + '/api/editor/images';
		this.editor.customConfig.uploadImgHeaders = {
			Authorization: 'Bearer ' + getToken()
		};

		this.editor.customConfig.pasteFilterStyle = false;

		// 忽略粘贴内容中的图片
		this.editor.customConfig.pasteIgnoreImg = true;

		this.editor.customConfig.pasteTextHandle = function(content) {
			let html = content;
			html = html.replace(/<xml>[\s\S]*?<\/xml>/gi, '');
			html = html.replace(/<style>[\s\S]*?<\/style>/gi, '');
			// html = html.replace(/<\/?[^>]*>/g, '')
			html = html.replace(/[ | ]*\n/g, '\n');
			html = html.replace(/&nbsp;/gi, '');
			html = html.replace(/\n(\n)*( )*(\n)*\n/gi, '\n');
			html = html.replace(/<!--\[if\s+gte\s+mso\s+[0-9]*\]>\s*<!\[endif\]-->/gi, '');
			return html;
		};

		this.editor.customConfig.onchange = html => {
			let text = this.editor.txt.text();
			if (this.cache) localStorage.editorCache = html;
			this.$emit('input', this.valueType === 'html' ? html : text);
			this.$emit('on-change', html, text);
		};
		this.editor.customConfig.onchangeTimeout = this.changeInterval;
		// create这个方法一定要在所有配置项之后调用
		this.editor.create();
		// 如果本地有存储加载本地存储内容
		let html = this.value || localStorage.editorCache;
		if (html) this.editor.txt.html(html);
	}
};
</script>

<style lang="less">
.editor-wrapper * {
	z-index: 100 !important;
}

.w-e-menu {
	z-index: 2 !important;
}

.w-e-text-container {
	z-index: 1 !important;
}
</style>
